<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function index()
    {
        $user=\Auth::user();
        $posts=Post::orderBy('created_at','desc')->paginate(6);
        $topics=[];
        return view('post/index',compact('posts','topics','user'));
    }

    public function show(Post $post)
    {
        return view('post/show',compact('post'));
    }

    public function create()
    {
        return view('post/create');
    }

    public function store(Request $request)
    {
//        tinker 写法
//        $post=new Post();
//        $post->title=\request('title');
//        $post->content=\request('content');
//        $post->save();

//        $params=['title'=>\request('title'),'content'=>\request('content')];
        $this->validate($request,[
            'title'=>'required|max:255|min:4',
            'content'=> 'required|min:100',
        ]);
//        $params=request(['title','content']);
        $params = array_merge(request(['title', 'content']), ['user_id' => \Auth::id()]);
        Post::create($params);
        return redirect("/posts");
    }
    public function imageUpload(Request $request)
    {
//        dd(request()->all());
        $path = $request->file('wangEditorH5File')->storePublicly(md5(\Auth::id() . time()));
        return asset('storage/'. $path);
    }
    public function edit(Post $post)
    {
        return view('post/edit', compact('post'));
    }

    public function update(Request $request, Post $post)
    {
        $this->validate($request, [
            'title' => 'required|max:255|min:4',
            'content' => 'required|min:100',
        ]);
//        权限控制
        $this->authorize('update', $post);
        $post->title=request('title');
        $post->content=request('content');
        $post->save();
//        $this->authorize('update', $post);
//
//        $post->update(request(['title', 'content']));
        return redirect("/posts/{$post->id}");
    }

    public function delete(Post $post)
    {
        $this->authorize('delete', $post);
        $post->delete();
        return redirect('/posts');
    }
}
